package cn.tt.tuantuanerp.passport.webapi.service.impl;


import cn.tt.tuantuanerp.passport.service.IUserService;
import cn.tt.tuantuanerp.passport.webapi.mapper.LoginLogMapper;
import cn.tt.tuantuanerp.passport.webapi.mapper.UserMapper;
import cn.tt.tuantuanerp.passport.webapi.mapper.UserRoleMapper;
import cn.tt.tuantuanerp.passport.webapi.security.UserDetails;
import cn.tt.tuantuanerp.tuantuanerp.comment.ex.ServiceException;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.dto.UserAddNewDTO;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.dto.UserLoginDTO;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.dto.UserUpdateDTO;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.entity.User;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.entity.UserRole;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.vo.*;
import cn.tt.tuantuanerp.tuantuanerp.comment.utils.Bean;
import cn.tt.tuantuanerp.tuantuanerp.comment.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaModel;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 用户业务实现类
 *
 * @author gudiwen
 * @version 0.0.1
 */
@Service
@Slf4j
@DubboService
public class UserServiceImpl implements IUserService {
    @Autowired
    UserMapper mapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    LoginLogMapper loginLogMapper;

    @Autowired
    com.aliyun.dysmsapi20170525.Client client;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    IUserService iUserService;

    @Value("${tuantuanerp.jwt.duration-in-minute}")
    private long durationInMinute;

    @Value("${tuantuanerp.jwt.secret-key}")
    private String secretKey;

    private static final int MAX_LOGIN_FAILS_TIMES = 5;

    @Override
    public String login(UserLoginDTO userLoginDTO,HttpServletRequest request) {
        log.debug("开始处理[管理员登录]的业务,请求参数是{}",userLoginDTO);
        if (userLoginDTO.getPassword()==null || userLoginDTO.getPassword().trim().isEmpty()){
            String message = "登录失败，密码不能为空";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        //认证用户信息
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                userLoginDTO.getAuthentication(), userLoginDTO.getPassword()
        );
        Authentication authenticate = null;
        try {
            authenticate = authenticationManager.authenticate(authentication);
            log.debug("返回结果:{}",authenticate);

        } catch (BadCredentialsException e) {
            //用户登录失败,修改剩余登录次数
            UserLoginInfoVO loginInfo = mapper.getLoginInfo(userLoginDTO.getAuthentication());
            int remainLoginTimes = (int) redisTemplate.opsForValue().get(Long.toString(loginInfo.getId())) -1;
            redisTemplate.opsForValue().set(Long.toString(loginInfo.getId()),remainLoginTimes);
            log.debug("用户登录剩余失败次数:{}",remainLoginTimes);
            if (remainLoginTimes<=0){
                log.debug("用户剩余登录失败次数为0,开始禁用该用户,id:{}",loginInfo.getId());
                iUserService.setDisEnable(loginInfo.getId());
                throw new DisabledException("登录失败，此账号已经禁用！");
            }else {
                throw new BadCredentialsException("密码错误,剩余登录次数:"+remainLoginTimes+"");
            }
        }

        //获取Authentication返回的User对象
        UserDetails user = (UserDetails) authenticate.getPrincipal();
        log.debug("Principal的结果:{}",user);
        //重置登录次数
        redisTemplate.opsForValue().set(Long.toString(user.getId()),MAX_LOGIN_FAILS_TIMES);
        log.debug("认证成功,准备生成JWT数据");
        Map<String,Object> claims = new HashMap<>();
        Long id = user.getId();
        claims.put("id",id);//向JWT中封装id
        claims.put("username",user.getUsername());//向JWT中封装username
        claims.put("ip",getIp(request));
        claims.put("phone",mapper.getStandardById(id).getPhone());
        //将ArrayList转为json字符串格式
        claims.put("authorities", JSON.toJSONString(user.getAuthorities()));//向JWT中封装权限信息
        //生成并返回jwt
        Date expirationDate = new Date(System.currentTimeMillis() + durationInMinute * 60 * 1000);
        String jwt = Jwts.builder()
                //Header
                .setHeaderParam("alg","HS256")//声明算法
                .setHeaderParam("typ","JWT")//声明类型
                //Payload
                .setClaims(claims)//设置token内容
                .setExpiration(expirationDate)//设置过期时间
                //Signature 签名,验证真伪,作用是保证 JWT 没有被篡改过。
                .signWith(SignatureAlgorithm.HS256,secretKey)//指定算法和盐
                .compact();
        log.debug("生成的jwt是{}",jwt);

        //修改登录日志
        UserLoginInfoVO userLoginInfoVO = new UserLoginInfoVO();
        BeanUtils.copyProperties(user,userLoginInfoVO);
        generateLoginLogger(userLoginInfoVO,request);
        return jwt;
    }

    @Override
    public String loginByValidCode(UserLoginDTO userLoginDTO,HttpServletRequest request) {
        String inputValidCode = userLoginDTO.getValidCode();
        String phone = userLoginDTO.getAuthentication();
        log.debug("开始处理[根据验证码登录]的请求,inputValidCode:{},phone:{}",inputValidCode,phone);
        if (mapper.countByPhone(phone)==0){
            String message = "发送验证码失败,没有绑定该手机号的账户";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        if (inputValidCode==null || inputValidCode.trim().isEmpty()){
            String message = "登录失败,验证码输入不能为空";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }
        // 判断用户输入的验证码是否正确
        String validCode = (String) redisTemplate.opsForValue().get(phone);
        log.debug("获取到Redis中的验证码:{}",validCode);
        if (validCode==null || validCode.isEmpty()){
            String message = "登录失败,验证码已过期";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }
        if (!inputValidCode.equals(validCode)){
            String message = "登录失败,验证码错误";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }

        //删除redis中验证码
        Boolean isDelete = redisTemplate.delete(phone);
        log.debug("验证码是否从redis中删除成功: {}",isDelete);
        //验证码验证成功,查询用户信息
        log.debug("验证码验证成功,开始生成jwt...");
        UserLoginInfoVO userLoginInfoVO = mapper.getLoginInfo(phone);
        //重置登录次数
        redisTemplate.opsForValue().set(Long.toString(userLoginInfoVO.getId()),MAX_LOGIN_FAILS_TIMES);
        //生成并返回jwt
        // jwt中数据
        Map<String,Object> claims = new HashMap<>();
        Long id = userLoginInfoVO.getId();
        claims.put("id",id);//向JWT中封装id
        claims.put("username",userLoginInfoVO.getUsername());//向JWT中封装username
        claims.put("ip",getIp(request));
        claims.put("phone",mapper.getStandardById(id).getPhone());
        //将ArrayList转为json字符串格式
        List<String> permissions = userLoginInfoVO.getPermissions();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        claims.put("authorities", JSON.toJSONString(authorities));//向JWT中封装权限信息
        Date expirationDate = new Date(System.currentTimeMillis() + durationInMinute * 60 * 1000);
        String jwt = Jwts.builder()
                //Header
                .setHeaderParam("alg","HS256")//声明算法
                .setHeaderParam("typ","JWT")//声明类型
                //Payload
                .setClaims(claims)//设置token内容
                .setExpiration(expirationDate)//设置过期时间
                //Signature 签名,验证真伪,作用是保证 JWT 没有被篡改过。
                .signWith(SignatureAlgorithm.HS256,secretKey)//指定算法和盐
                .compact();
        log.debug("生成的jwt是{}",jwt);
        //修改登录日志
        generateLoginLogger(userLoginInfoVO,request);
        return jwt;
    }

    /**
     * 修改登录日志
     * @param userLoginInfoVO 用户登录信息
     * @param request 用来获取用户ip
     */
    public void generateLoginLogger(UserLoginInfoVO userLoginInfoVO,HttpServletRequest request){
        log.debug("用户的登录信息:{}",userLoginInfoVO);
        //更改用户最后登录时间
        User updateUser = new User();
        updateUser.setId(userLoginInfoVO.getId());
        updateUser.setGmtLastLogin(LocalDateTime.now());
        mapper.updateById(updateUser);

        //添加登录日志
        LoginLogVO loginLogVO = new LoginLogVO();
        loginLogVO.setUsername(userLoginInfoVO.getUsername());
        loginLogVO.setUserId(userLoginInfoVO.getId());
        loginLogVO.setGmtLogin(LocalDateTime.now());
        loginLogVO.setIp(getIp(request));
        log.debug("开始添加登录日志");
        int rows = loginLogMapper.insert(loginLogVO);
        if (rows==0){
            String message = "登录失败,服务器忙,请稍后再试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void logout() {
        log.debug("执行[用户退出]操作");
        // 清除SecurityContext中认证信息

        SecurityContextHolder.getContext().setAuthentication(null);
    }

    @Override
    public void sendValidCode(String phone) {
        log.debug("开始处理[发送验证码]的业务,phone:{}",phone);
        if (redisTemplate.hasKey(phone)){
            String message = "已发送验证码,请勿重复提交,三分钟后可再次发送";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }
        UserLoginInfoVO loginInfo = mapper.getLoginInfo(phone);
        if (loginInfo==null){
            String message = "发送验证码失败,没有绑定该手机号的账户";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        if (loginInfo.getEnable()==0){
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,"登录失败,该账号已被禁用");
        }

        //发送验证码
        String code = Integer.toString((int)(Math.random()*1000000));
        log.debug("短信验证码为:{}",code);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\""+code+"\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
            com.aliyun.teaconsole.Client.log("短信服务响应结果:"+ Common.toJSONString(TeaModel.buildMap(resp)));
        } catch (Exception e) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,"服务器发生未知错误,请联系管理员");
        }
        // 将生成的验证码保存到redis里,并设置过期时间
        log.debug("将生成的验证码redis里,过期时间为2分钟,手机号:{},验证码:{}",phone,code);
        redisTemplate.opsForValue().set(phone,code,100, TimeUnit.SECONDS);
    }

    private String getIp(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
//        X-Real-IP：nginx代理
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    @Override
    public void addNew(UserAddNewDTO userAddNewDTO) {
        log.debug("开始进行新增用户的业务,用户信息:{}",userAddNewDTO);
        Long[] roleIds = userAddNewDTO.getRoleIds();
        if (roleIds.length < 1){
            String message = "添加失败,未添加用户角色信息";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        // 最高权限管理员(默认id为1)不允许添加
        for (Long roleId : roleIds) {
            if (roleId == 1){
                String message = "添加失败,该数据不合法";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
            }
        }
        log.debug("检查用户登录名是否存在");
        if (mapper.getStandardByLoginName(userAddNewDTO.getLoginName()) != null) {
            String message = "用户的登录名已存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        log.debug("检查用户电话是否存在");
        if (mapper.countByPhone(userAddNewDTO.getPhone()) > 0) {
            String message = "用户的电话已存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        log.debug("检查用户邮箱是否存在");
        if (mapper.countByEmail(userAddNewDTO.getEmail()) > 0) {
            String message = "用户的邮箱已存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        User user = new User();
        //用户默认设置
        user.setStatus(1);//默认在职
        user.setEnable(1);//默认启用
        user.setGmtCreate(LocalDateTime.now());
        user.setGmtModified(LocalDateTime.now());

        BeanUtils.copyProperties(userAddNewDTO,user, Bean.getNullPropertyNames(userAddNewDTO));
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        log.debug("开始向数据库插入用户信息,参数:{}",user);
        int rows = mapper.insert(user);
        //判断插入数据的结果是否符合预期
        if (rows != 1){//磁盘满时,会插入失败
            String message = "添加管理员失败,服务器忙,请稍后再次尝试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        log.debug("插入用户信息成功,参数:{}",user);

        List<UserRole> list = new ArrayList<>();
        for (Long roleId : roleIds) {
            UserRole adminRole = new UserRole();
            adminRole.setUId(user.getId());
            adminRole.setRoleId(roleId);
            adminRole.setGmtCreate(LocalDateTime.now());
            list.add(adminRole);
        }
        log.debug("插入的数据是list={}",list);
        rows = userRoleMapper.insertBatch(list);
        if (rows != roleIds.length){
            String message = "添加用户失败,服务器忙,请稍后再次尝试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始进行删除用户的业务,用户id:{}",id);
        // 不允许删除最高管理员(默认id为1)
        if (id == 1){
            String message = "删除失败,访问数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        UserStandardVO isExist = mapper.getStandardById(id);
        if (isExist == null){
            String message = "删除失败,用户信息不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        log.debug("开始执行删除用户操作,参数id为{}",id);
        int rows = mapper.deleteById(id);
        if (rows != 1){
            String message = "删除用户失败,服务器忙,请稍后再次尝试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }

        //删除用户角色关联数据
        rows = userRoleMapper.deleteByUserId(id);
        if (rows < 1){
            String message = "删除用户失败,服务器忙,请稍后再次尝试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }

        log.debug("删除成功");
    }

    @Override
    public List<UserListItemVO> list() {
        log.debug("开始处理[查询用户列表]的业务");
        return selectList(null,null,null);
    }

    @Override
    public List<UserListItemVO> listByUsername(String username) {
        log.debug("开始处理[查询根据用户名用户列表]的业务");
        return selectList(username, null, null);
    }

    @Override
    public List<UserListItemVO> listByLoginName(String loginName) {
        log.debug("开始处理[查询根据登录名用户列表]的业务");
        return selectList(null, loginName, null);
    }

    @Override
    public List<UserListItemVO> listByEnable(Integer enable) {
        log.debug("开始处理[查询根据是否启用用户列表]的业务");
        return selectList(null, null, enable);
    }

    public List<UserListItemVO> selectList(String username,String loginName,Integer enable) {
        List<UserListItemVO> list;
        if (username!=null){
            username = "%"+username+"%";
            list = mapper.listByUsername(username);
        }else if (loginName!=null){
            loginName = "%"+loginName+"%";
            list = mapper.listByLoginName(loginName);
        }else if (enable!=null){
            list = mapper.listByEnable(enable);
        }else {
            list = mapper.list();
        }
        log.debug("查询成功");
        //删除列表中root用户的数据,避免在前端列表中操作该数据
        Iterator<UserListItemVO> iterator = list.iterator();
        while (iterator.hasNext()){
            if (iterator.next().getId()==1){
                iterator.remove();
                break;
            }
        }
        return list;
    }

    @Override
    public UserDetailsVO getUserDetailsVOById(Long id) {
        log.debug("开始处理[查询用户详情]的业务,id:{}",id);
        UserDetailsVO userDetailsVO = mapper.getUserDetailsVOById(id);
        if (userDetailsVO==null){
            String message = "查询用户详情失败,用户不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        log.debug("[查询用户详情]成功");
        return userDetailsVO;
    }

    @Override
    public void validPassword(Long id,String inputPassword) {
        log.debug("开始处理比较密码,id:{},inputPassword:{}",id,inputPassword);
        String passwordById = mapper.getPasswordById(id);
        if (passwordById==null){
            String message = "服务器忙,请稍后再试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        boolean matches = passwordEncoder.matches(inputPassword, passwordById);
        if (!matches){
            String message = "原密码错误";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        log.debug("验证原密码成功");
    }

    @Override
    public void updateById(Long id, UserUpdateDTO userUpdateDTO) {
        log.debug("开始处理[修改用户信息]的业务,用户信息:{}",userUpdateDTO);
        if (mapper.getUserDetailsVOById(id)==null){
            String message = "修改用户详情失败,用户不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        //修改用户信息
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO,user);

        //密码加密
        String password = userUpdateDTO.getPassword();
        if (password!=null){
            String encodePassword = passwordEncoder.encode(password);
            user.setPassword(encodePassword);
        }
        user.setId(id);
        {
            int rows = mapper.updateById(user);
            if (rows == 0) {//磁盘满时,会插入失败
                String message = "修改用户信息失败,服务器忙,请稍后再次尝试!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
            log.debug("修改用户信息成功");
        }

        //新增用户角色信息
        List<Long> rolesId = userUpdateDTO.getRoles();
        if (rolesId != null && rolesId.size() != 0){
            log.debug("开始修改用户角色信息:先删除原有的用户角色信息");
            {
                int rows = userRoleMapper.deleteByUserId(id);
                if (rows == 0) {
                    String message = "修改用户信息失败,服务器忙,请稍后再次尝试!";
                    log.warn(message);
                    throw new ServiceException(ServiceCode.ERR_UPDATE, message);
                }
            }

            log.debug("开始新增用户角色信息");
            {
                List<UserRole> userRolesList = new ArrayList<>();
                for (Long rid : rolesId) {
                    UserRole userRole = new UserRole();
                    userRole.setUId(id);
                    userRole.setRoleId(rid);
                    userRolesList.add(userRole);
                }
                int rows = userRoleMapper.insertBatch(userRolesList);
                if (rows == 0) {
                    String message = "修改用户信息失败,服务器忙,请稍后再次尝试!";
                    log.warn(message);
                    throw new ServiceException(ServiceCode.ERR_UPDATE, message);
                }
            }
        }
        log.debug("修改用户信息成功");
    }

    @Override
    public void setEnable(Long id) {
        updateEnableById(id,1);
        //重置登录次数
        redisTemplate.opsForValue().set(Long.toString(id),MAX_LOGIN_FAILS_TIMES);
    }

    @Override
    public void setDisEnable(Long id) {
        updateEnableById(id,0);
    }

    private void updateEnableById(Long id,Integer enable) {
        log.debug("需要修改的用户id:{}的的enable属性",id);
        String tip = enable==1?"启用":"禁用";
        UserDetailsVO userDetailsVO = mapper.getUserDetailsVOById(id);
        if (userDetailsVO==null){
            log.debug("用户不存在");
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"修改失败,用户ID不存在");
        }

        //判断状态是否冲突
        if (userDetailsVO.getEnable()==enable){
            String message = tip + "用户失败,已"+tip+"该用户";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }

        //修改enable状态
        log.debug("需要修改的用户id:{},enable修改为[{}]:",id,tip);
        User user = new User();
        user.setId(id);
        user.setEnable(enable);
        int row = mapper.updateById(user);

        //判断是否修改成功
        if (row!=1){
            String message = tip + "用户失败,服务器忙,请稍后再试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
        log.debug("修改状态为[{}]成功",tip);
    }

    @Override
    public void forgetPassword(String authentication) {
        log.debug("开始进行[重置密码]的业务,用户的登录信息是:{}",authentication);
        if (authentication == null){
            String message = "重置密码失败,传入的登录信息有误!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        User user = new User();
        user.setId(mapper.getIdByAuthentication(authentication));
        user.setPassword(passwordEncoder.encode("123456"));
        log.debug("即将重置的用户信息为:{}",user);
        mapper.updateById(user);
    }
}
